package com.xrj4j.k_tally.view

import android.annotation.SuppressLint
import android.content.Context
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Search
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Card
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.constraintlayout.compose.ConstraintLayout
import com.xrj4j.k_tally.R
import com.xrj4j.k_tally.db.AppDatabase
import com.xrj4j.k_tally.model.BillItem
import com.xrj4j.k_tally.ui.theme.K_tallyTheme
import com.xrj4j.k_tally.view.viewmodel.BillItemViewModel

@Composable
fun HomeScreen(
    modifier: Modifier = Modifier
) {
    Column(modifier = Modifier) {
        HomeHeader()
        HomeBody()
    }
}

@Composable
fun HomeHeader() {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .height(50.dp),
        horizontalArrangement = Arrangement.SpaceBetween,
        verticalAlignment = Alignment.CenterVertically
    ) {
        Text(text = "简约记账")
        Image(imageVector = Icons.Default.Search, contentDescription = null)
    }
}

@Composable
fun HomeBody() {
    val context = LocalContext.current
    val billViewModel by remember {
        mutableStateOf(BillItemViewModel(AppDatabase.getInstance(context).getBillDao()))
    }
    val itemList = billViewModel.loadList().collectAsState(initial = listOf())
    Column {
        HomeBodyCard()
        TodayList(itemList.value, {}, {})
    }
}

@Composable
fun HomeBodyCard() {
    Card {
        ConstraintLayout(
            modifier = Modifier
                .padding(20.dp)
                .fillMaxWidth(),
        ) {
            val (outText, icon, outcome, income, monthBudget, restBudget) = createRefs()
            Text(text = "本月支出",
                modifier = Modifier.constrainAs(outText) {
                    top.linkTo(parent.top)
                    start.linkTo(parent.start)
                })
            Icon(
                painter = painterResource(id = R.mipmap.ih_show),
                contentDescription = null,
                modifier = Modifier.constrainAs(icon) {
                    end.linkTo(parent.end, 20.dp)
                    bottom.linkTo(outText.bottom)
                }
            )
            Text(
                text = "￥400",
                modifier = Modifier.constrainAs(outcome) {
                    start.linkTo(parent.start)
                    top.linkTo(outText.top, 30.dp)
                },
                fontWeight = FontWeight.Bold,
                style = MaterialTheme.typography.titleLarge
            )

            Row(modifier = Modifier.constrainAs(monthBudget) {
                end.linkTo(parent.end)
                bottom.linkTo(outcome.bottom)
            }) {
                Text(text = "本月预算")
                Spacer(modifier = Modifier.width(5.dp))
                Text(text = "￥500", fontWeight = FontWeight.Bold)
            }
            Row(modifier = Modifier.constrainAs(income) {
                start.linkTo(parent.start)
                top.linkTo(outcome.bottom, 20.dp)
            }) {
                Text(text = "本月支出")
                Spacer(modifier = Modifier.width(5.dp))
                Text(text = "￥500", fontWeight = FontWeight.Bold)
            }

            Row(modifier = Modifier.constrainAs(restBudget) {
                end.linkTo(parent.end)
                bottom.linkTo(income.bottom)
            }) {
                Text(text = "预算剩余")
                Spacer(modifier = Modifier.width(5.dp))
                Text(text = "￥500", fontWeight = FontWeight.Bold)
            }
        }
    }
}

@Composable
fun TodayList(
    itemList: List<BillItem>,
    onRemoveItem: (BillItem) -> Unit,
    onEditItem: (BillItem) -> Unit,
) {
    Column(
        modifier = Modifier.fillMaxWidth(),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Row(modifier = Modifier.padding(horizontal = 10.dp, vertical = 20.dp)) {
            Text(
                text = "今日支出 ￥100 收入 ￥100",
                color = MaterialTheme.colorScheme.primary.copy(0.74f),
                style = MaterialTheme.typography.bodySmall
            )
        }
        LazyColumn {
            items(itemList) {
                BillItemRow(
                    it,
                    deleteItem = onRemoveItem,
                    editItem = onEditItem
                )
            }
        }

        Text(
            text = if (itemList.isEmpty()) "还没有记账..." else "我是有底线的...",
            modifier = Modifier.padding(top = 10.dp),
            color = MaterialTheme.colorScheme.onSurface.copy(0.74f),
            style = MaterialTheme.typography.bodySmall
        )
    }
}


@Composable
fun BillItemRow(
    item: BillItem,
    deleteItem: (BillItem) -> Unit,
    editItem: (BillItem) -> Unit
) {
    ConstraintLayout(
        modifier = Modifier
            .background(
                MaterialTheme.colorScheme.primary.copy(alpha = 0.1f),
                shape = MaterialTheme.shapes.medium
            )
            .pointerInput(Unit) {
                detectTapGestures(
                    onLongPress = { deleteItem(item) },
                    onTap = { editItem(item) }
                )
            }
            .fillMaxWidth()
    ) {
        val (icon, type, remark, money, time) = createRefs()
        Icon(
            painter = painterResource(id = item.typeIcon),
            contentDescription = null,
            tint = Color.Unspecified,
            modifier = Modifier
                .size(50.dp)
                .constrainAs(icon) {
                    top.linkTo(parent.top, 10.dp)
                    bottom.linkTo(parent.bottom, 10.dp)
                    start.linkTo(parent.start, 10.dp)
                }
        )

        Text(
            text = item.typeName,
            modifier = Modifier.constrainAs(type) {
                start.linkTo(icon.end, 10.dp)
                top.linkTo(icon.top)
            },
            style = MaterialTheme.typography.bodySmall
        )
        Text(
            text = item.remark,
            modifier = Modifier.constrainAs(remark) {
                start.linkTo(type.start)
                bottom.linkTo(icon.bottom)
            },
            style = MaterialTheme.typography.bodySmall
        )
        Text(
            text = "￥${item.money}",
            modifier = Modifier.constrainAs(money) {
                end.linkTo(parent.end, 10.dp)
                top.linkTo(icon.top)
            },
            style = MaterialTheme.typography.bodySmall
        )
        Text(
            text = item.createTime,
            modifier = Modifier.constrainAs(time) {
                end.linkTo(parent.end, 10.dp)
                bottom.linkTo(icon.bottom)
            },
            style = MaterialTheme.typography.bodySmall
        )
        Spacer(
            modifier = Modifier
                .height(2.dp)
                .fillMaxWidth()
                .background(MaterialTheme.colorScheme.surface)
        )

    }

}

@Composable
fun MyDialog(
    keyword: String = "",
    showDialog: MutableState<Boolean>,
    confirm: () -> Unit,
    dismiss: () -> Unit,
) {
    if (showDialog.value) {
        AlertDialog(
            onDismissRequest = {
                dismiss()
            },
            title = {
                Text(text = "提醒")
            },
            text = {
                Text(
                    "删除后无法恢复, 确定要删除${keyword}吗?"
                )
            },
            confirmButton = {
                TextButton(
                    onClick = {
                        confirm()
                        showDialog.value = false
                    }
                ) {
                    Text("确定")
                }
            },
            dismissButton = {
                TextButton(
                    onClick = {

                    }
                ) {
                    Text("取消")
                }
            }
        )
    }
}


@Composable
@Preview(showBackground = true)
fun HomeScreenPreview() {
    K_tallyTheme {
        HomeScreen()
    }
}
